import { defineStore } from 'pinia'
import { ref,computed} from 'vue'
import { useUserStore } from './user'
import {insertCartAPI,findNewCartListAPI,delCartAPI} from '@/apis/cart'

export const useCartStore = defineStore('cart',()=>{
    const userStore = useUserStore()
    const isLogin = computed(()=>userStore.userInfo.token)
    const cartList = ref([])
    // 添加购物车
    const addCart=async(goods)=>{
        const {skuId,count} = goods
        // 登录账号之后的加入购物车逻辑
        if(isLogin.value){
            await insertCartAPI({skuId,count})
            updateNewList()
        } else {
            // 添加购物车操作
        // 已添加过
       const item = cartList.value.find((item)=>goods.skuId===item.skuId)
       if(item){
        item.count++
       }else {
        // 没有添加过
        cartList.value.push(goods)
       }
        }
    }
    // 删除购物车
    const delCart=async(skuId)=>{
        if(isLogin.value){
            await delCartAPI([skuId])
             updateNewList()
        }else {
            const idx = cartList.value.findIndex((item)=>skuId===item.skuId)
        cartList.value.splice(idx,1)
        }
    }

    // 清除购物车
    const clearCart =()=>{
        cartList.value = []
    }
    // 获取最新购物车列表的action
    const updateNewList =async()=>{
        const res = await findNewCartListAPI()
            cartList.value = res.result
    }

    // 单选功能
    const singleCheck=(skuId,selected)=>{
        const item = cartList.value.find((item)=>item.skuId===skuId)
        item.selected = selected
    }
    // 全选功能
    const allCheck = (selected)=>{
        cartList.value.forEach((item)=>item.selected = selected)
    }

    // 计算属性
    // 商品总数量
    const allCount = computed(()=>cartList.value.reduce((a,c)=>a+c.count,0))
    // 商品总价
    const allPrice = computed(()=>cartList.value.reduce((a,c)=>a+c.count*c.price,0))
    // 已选择数量
    const selectedCount = computed(()=>cartList.value.filter(item=>item.selected).reduce((a,c)=>a+c.count,0))
    // 已选择商品价钱总和
    const selectedPrice = computed(()=>cartList.value.filter(item=>item.selected).reduce((a,c)=>a+c.count*c.price,0))
    // 是否全选
    const isAll = computed(()=>cartList.value.every((item)=>item.selected))

    return {cartList,updateNewList,clearCart,addCart,selectedPrice,selectedCount,delCart,allCheck,allCount,allPrice,singleCheck,isAll}
},{
    persist:true,
})